<template>
    <div class="home">
        <div class="home-cetent">
            <van-form @submit="onSubmit">
                <div class="onSubmiTtitle">企业微信定时任务</div>
                <van-cell-group inset>
                    <van-field v-model="message" rows="1" autosize label="发送消息" type="textarea"
                        placeholder="请输入需要发送的消息" />
                    <van-field name="uploader" label="文件上传">
                        <template #input>
                            <van-uploader v-model="upImg" :after-read="afterRead" multiple max-count="1"
                                :before-delete="deleteImage" />
                        </template>
                    </van-field>
                    <van-field v-model="resultDate" is-link readonly name="datePicker" label="时间日期" placeholder="点击选择日期"
                        @click="showPicker = true" />
                    <van-popup v-model:show="showPicker" destroy-on-close position="bottom">
                        <van-date-picker :model-value="pickerValue" @confirm="onConfirmdata"
                            @cancel="showPicker = false" />
                    </van-popup>
                    <van-field v-model="result" is-link readonly name="calendar" label="定时时间" placeholder="点击选择定时时间"
                        @click="showCalendar = true" />
                </van-cell-group>
                <div style="margin: 16px;">
                    <van-button round block type="primary" native-type="submit">
                        设置定时任务
                    </van-button>
                    <van-button round block type="primary" class="mgtop" @click="onSubmitList">
                        {{ showCalendarlist ? "关闭" : "打开" }}定时任务记录
                    </van-button>
                </div>
            </van-form>
            <van-popup v-model:show="showCalendar" position="bottom">
                <van-time-picker @confirm="onConfirm" @cancel="showCalendar = false" />
            </van-popup>
        </div>
        <!-- 填写api 机器人 -->
        <van-dialog v-model:show="showcalse" title="请填写企业微信机器人API" :before-close="onBeforeClose"
            @confirm="onConfirmDialog">
            <div class="APIcontent">
                <van-field v-model="QYinputValue" placeholder="请填写企业微信机器人API" />
            </div>
        </van-dialog>
        <!-- 定时任务列表 -->
        <div class="home-cetent-list" v-if="showCalendarlist">
            <div class="onSubmiTtitle">定时任务列表 <span @click="getUserRequestTimeList">刷新列表</span> </div>
            <van-loading size="24px" v-if="isLoading" color="#1989fa" vertical>加载中...</van-loading>

            <div class="video-content">
                <div class="video-content-li" v-for=" ( item, index)  in defaultList" :key="index">
                    创建日期：<span>{{ item.createTime }}</span> 定时时间：<span>{{ item.resultDate }}</span> <span
                        :class="[item.status == 1 || item.status == 3 ? 'color_r' : 'color_c']">{{
                            item.status == 1 ? "已执行" : item.status == 2 ? "未执行" : '已取消' }}</span> <span
                        v-if="item.status == 2" @click="cancelTask(item.job_id)">取消定时</span>
                </div>
                <div class="error" v-if="defaultList.length == 0">
                    暂无数据，请添加定时任务
                </div>
                <!-- <van-barrage :v-model="messages" :speed="100" :auto-play="true">
                    <template #content="{ message }">
                        <span @click="handleClick(message)">{{ message }}</span>
                    </template>
                </van-barrage> -->
                <!-- <van-barrage v-model="list">
                    <template #content="{ message }">
                        <span @click="handleBarrageClick(message)" style="cursor: pointer;">{{ message }}</span>
                    </template>
                    <div class="video" style="width: 100%; height: 150px"></div>
                </van-barrage> -->
            </div>
        </div>
    </div>

</template>

<script lang="ts" setup>
import { userRequestTime, getUnexecutedTask, cancelTaskPamars } from '@/apis/api/user';
import { uploadImage } from '@/utils/methods'
import { showSuccessToast, showFailToast } from 'vant';
import { ref } from 'vue';
const message = ref('');
const upImg = ref([]);
const result = ref('');
const resultDate = ref('');
const showPickerDate = ref(false);
// image 名称
const imageName = ref('');
// 日期
const showPicker = ref(false);
// 弹出框
const showcalse = ref(true);
// 企业微信机器人API
const QYinputValue = ref('');
const pickerValue = ref([]);
const isLoading = ref(false);
// 显示、隐藏定时任务
const showCalendarlist = ref(false);
const onConfirmdata = ({ selectedValues }: any) => {
    console.log(selectedValues, 66)
    resultDate.value = selectedValues.join('-');
    showPicker.value = false;
};
interface TaskItem {
    webhookurl: string;
    imagepath: string;
    message: string;
    resultDate: Date;
    id: Number;
    createTime: Date
    status: Number;
    job_id: string;
}
const defaultList = ref<TaskItem[]>([]);


// 清除 - 重置
const clear = () => {
    message.value = "";
    upImg.value = [];
    result.value = '';
    resultDate.value = '';
    // image 名称
    imageName.value = '';
    pickerValue.value = [];
    getUserRequestTimeList()
};
const onBeforeClose = (action: any, done: any) => {
    if (action === "confirm") {
        return false;
    } else {
        return true;
    }
};
// 点击api弹窗确认
const onConfirmDialog = () => {
    if (!QYinputValue.value) {
        showFailToast('请填写企业微信机器人API');
        return true;
    } else {
        showcalse.value = false;
        return false;
    }

};
interface UserRequestTimeResponse {
    status: number;
    message: string;
}
// 定时任务返回参数定义
interface UserRequestTimeTaskResponse {
    status: number;
    message: string;
    list: any[];
}
// 获取定时任务列表
const getUserRequestTimeList = async () => {
    isLoading.value = true;
    const data = {
        webhook_url: QYinputValue.value
    };
    const res = await getUnexecutedTask(data) as UserRequestTimeTaskResponse;
    if (res.status != 1) {
        showFailToast(res.message);
        isLoading.value = false;
        return;
    } else {
        defaultList.value = res?.list;
        isLoading.value = false;
        return;
    }
};
const showCalendar = ref(false);
const onConfirm = (date: any) => {
    result.value = date['selectedValues'][0] + ':' + date['selectedValues'][1] + ':00';
    showCalendar.value = false;
};
const afterRead = async (file: any) => {
    // 此时可以自行将文件上传至服务器
    console.log(file);
    const files = file.file || null;
    const res = await uploadImage(files);
    imageName.value = file.file.name;
};
const onSubmit = async (values: any) => {
    if (!message.value && !result.value && !resultDate.value) {
        showFailToast('请完善信息再提交');
        return;
    }
    const data = {
        message: message.value,
        send_time: result.value,
        imageName: imageName.value,
        send_data: resultDate.value,
        webhook_url: QYinputValue.value
    };
    const res = await userRequestTime(data) as UserRequestTimeResponse;
    if (res.status != 1) {
        showFailToast(res.message);
        return;
    } else {
        showSuccessToast(res.message);
        clear();
        return;
    }
};
const deleteImage = () => {
    upImg.value = [];
    imageName.value = '';
};
const onSubmitList = () => {
    console.log('定时任务记录');
    showCalendarlist.value = !showCalendarlist.value;
    if (showCalendarlist.value) {
        getUserRequestTimeList()
    }
};

interface CancelTaskResponse {
    status: number;
    message: string;
}
// 取消定时任务
const cancelTask = async (job_id: string) => {
    console.log('取消定时任务id', job_id);
    const data = {
        job_id: job_id
    };
    // 取消定时任务
    const res = await cancelTaskPamars(data) as CancelTaskResponse;
    if (res.status != 1) {
        showFailToast(res.message);
        return;
    } else {
        showSuccessToast(res.message);
        getUserRequestTimeList()
        return;
    }
};
</script>
<style scoped lang="scss">
.home {
    padding: 16px;
    box-sizing: border-box;

    .home-cetent {
        width: 100%;
        background: #E4E4E4;
        padding: 10px;
        box-sizing: border-box;
        border-radius: 6px;

        .onSubmiTtitle {
            font-size: 20px;
            font-weight: bold;
            margin: 10px 0 20px;
            text-align: center;


        }
    }

    .mgtop {
        margin-top: 20px;
    }

    .home-cetent-list {
        width: 100%;
        padding: 10px;
        box-sizing: border-box;

        .onSubmiTtitle {
            font-size: 20px;
            font-weight: bold;
            margin: 10px 0 20px;
            text-align: center;

            span {
                font-size: 14px !important;
                color: #409EFF;
                font-weight: 200;
            }
        }

    }

    .APIcontent {
        border: 1px solid #ebedf0;
        margin: 10px;
        border-radius: 10px;
    }

    ::v-deep .van-field {
        border-radius: 10px;
    }

    .video-content {
        width: 100%;
        height: 290px;
        overflow-y: auto;

        .video-content-li {
            width: 100%;
            // height: 40px;
            border-bottom: 1px solid #ebedf0;
            padding: 10px;
            box-sizing: border-box;
            font-size: 14px;

            span {
                margin-right: 10px;
            }

            &:nth-child(1) {
                border-top: 1px solid #ebedf0;

            }
        }
    }
}

.color_r {
    color: red;
}

.color_c {
    color: #409EFF;
}

.error {
    margin-top: 20px;
    font-size: 14px;
    color: #ccc;
    text-align: center;
}
</style>